<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><div id="myscoll"></div><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Axios | 晚夜微雨问海棠のBlog</title><meta name="keywords" content="Axios"><meta name="author" content="晚夜微雨问海棠"><meta name="copyright" content="晚夜微雨问海棠"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="这是小生对 Axios 的一些拙见,有不对之处还望评论区留言,以便及时更正  Json-server 包 搭建REST APIjson-server 是什么？ 用来快速搭建模拟的 REST API 的工具包  使用 json-server 在线文档：https:&#x2F;&#x2F;github.com&#x2F;typicode&#x2F;json-server  可以在 30s内搭建一个 假的 api 服务  安装：  1npm">
<meta property="og:type" content="article">
<meta property="og:title" content="Axios">
<meta property="og:url" content="http://example.com/posts/6155a9d6.html">
<meta property="og:site_name" content="晚夜微雨问海棠のBlog">
<meta property="og:description" content="这是小生对 Axios 的一些拙见,有不对之处还望评论区留言,以便及时更正  Json-server 包 搭建REST APIjson-server 是什么？ 用来快速搭建模拟的 REST API 的工具包  使用 json-server 在线文档：https:&#x2F;&#x2F;github.com&#x2F;typicode&#x2F;json-server  可以在 30s内搭建一个 假的 api 服务  安装：  1npm">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pianshen.com%2Fimages%2F392%2Fc8f82846ea9401c8fbcb4428a7269870.png&refer=http%3A%2F%2Fwww.pianshen.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664443051&t=4db5e4c8373f1a1e24d8a9a048367a1b">
<meta property="article:published_time" content="2022-11-12T03:28:51.665Z">
<meta property="article:modified_time" content="2022-09-09T05:52:11.163Z">
<meta property="article:author" content="晚夜微雨问海棠">
<meta property="article:tag" content="Axios">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pianshen.com%2Fimages%2F392%2Fc8f82846ea9401c8fbcb4428a7269870.png&refer=http%3A%2F%2Fwww.pianshen.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664443051&t=4db5e4c8373f1a1e24d8a9a048367a1b"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/posts/6155a9d6"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/manifest.json"/><meta name="msapplication-TileColor" content="#49b1f5"/><link rel="apple-touch-icon" sizes="180x180" href="/img/siteicon/128.png"/><link rel="icon" type="image/png" sizes="32x32" href="/img/siteicon/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/img/siteicon/16.png"/><link rel="mask-icon" href="/img/siteicon/128.png" color="#5bbad5"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":150},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":650,"languages":{"author":"作者: 晚夜微雨问海棠","link":"链接: ","source":"来源: 晚夜微雨问海棠のBlog","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Axios',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-09-09 13:52:11'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"> <link rel="stylesheet" href="/swiper/swiper.min.css"> <link rel="stylesheet" href="/swiper/swiperstyle.css"> <link rel="stylesheet" href="/css/rightMenu.css"> <link rel="stylesheet" href="/css/constrain.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-card-history/baiduhistory/css/main.css"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://cdn.cbd.int/anzhiyu-blog@2.0.3/css/runtime/runtime.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-swiper-anzhiyu@1.0.4/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-swiper-anzhiyu@1.0.4/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://cdn.cbd.int/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/atom.xml" title="晚夜微雨问海棠のBlog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://img2.woyaogexing.com/2022/06/28/de1ce3dc65468fd4!400x400.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">31</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">17</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/bangumis/index.html"><i class="fa-fw fas fa-home"></i><span> 追番</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活馆</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="http://81.69.189.243:8082/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pianshen.com%2Fimages%2F392%2Fc8f82846ea9401c8fbcb4428a7269870.png&amp;refer=http%3A%2F%2Fwww.pianshen.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1664443051&amp;t=4db5e4c8373f1a1e24d8a9a048367a1b')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">晚夜微雨问海棠のBlog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/bangumis/index.html"><i class="fa-fw fas fa-home"></i><span> 追番</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活馆</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="http://81.69.189.243:8082/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Axios</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-12T03:28:51.665Z" title="发表于 2022-11-12 11:28:51">2022-11-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-09-09T05:52:11.163Z" title="更新于 2022-09-09 13:52:11">2022-09-09</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>15分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Axios"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><div class="tip warning"><p>这是小生对 Axios 的一些拙见,有不对之处还望评论区留言,以便及时更正</p>
</div>
<h1 id="Json-server-包-搭建REST-API"><a href="#Json-server-包-搭建REST-API" class="headerlink" title="Json-server 包 搭建REST API"></a>Json-server 包 搭建REST API</h1><h2 id="json-server-是什么？"><a href="#json-server-是什么？" class="headerlink" title="json-server 是什么？"></a>json-server 是什么？</h2><ol>
<li>用来快速搭建模拟的 REST API 的工具包</li>
</ol>
<h2 id="使用-json-server"><a href="#使用-json-server" class="headerlink" title="使用 json-server"></a>使用 json-server</h2><ol>
<li><p>在线文档：<a target="_blank" rel="noopener" href="https://github.com/typicode/json-server">https://github.com/typicode/json-server</a></p>
</li>
<li><p>可以在 30s内搭建一个 假的 api 服务</p>
</li>
<li><p>安装：</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install -g json-server</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>目标根目录下创建数据库 json 文件：db.json 创建文件：</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">&quot;posts&quot;</span>: [</span><br><span class="line">    &#123; <span class="string">&quot;id&quot;</span>: <span class="number">1</span>, <span class="string">&quot;title&quot;</span>: <span class="string">&quot;json-server&quot;</span>, <span class="string">&quot;author&quot;</span>: <span class="string">&quot;typicode&quot;</span> &#125;</span><br><span class="line">  ],</span><br><span class="line">  <span class="string">&quot;comments&quot;</span>: [</span><br><span class="line">    &#123; <span class="string">&quot;id&quot;</span>: <span class="number">1</span>, <span class="string">&quot;body&quot;</span>: <span class="string">&quot;some comment&quot;</span>, <span class="string">&quot;postId&quot;</span>: <span class="number">1</span> &#125;</span><br><span class="line">  ],</span><br><span class="line">  <span class="string">&quot;profile&quot;</span>: &#123; <span class="string">&quot;name&quot;</span>: <span class="string">&quot;typicode&quot;</span> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>启动服务：</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">json-server --watch db.<span class="property">json</span></span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>延时响应：</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">json-server --watch db.<span class="property">json</span> -d <span class="number">2000</span></span><br></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>
<h1 id="axios"><a href="#axios" class="headerlink" title="axios"></a>axios</h1><ol>
<li>前端最流行的 ajax 请求库</li>
<li>react/vue 官方都推荐使用 axios 发 ajax 请求</li>
<li>文档: <a target="_blank" rel="noopener" href="https://github.com/axios/axios">https://github.com/axios/axios</a></li>
</ol>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><ol>
<li><p>Axios 是一个基于 <em><a target="_blank" rel="noopener" href="https://javascript.info/promise-basics">promise</a></em> 网络请求库，作用于<a target="_blank" rel="noopener" href="https://nodejs.org/"><code>node.js</code></a> 和浏览器中。</p>
</li>
<li><p>安装:</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install axios</span><br></pre></td></tr></table></figure>
<p>cdn:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;script src=<span class="string">&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;</span>&gt;&lt;/script&gt;</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>特性：</p>
<blockquote>
<ul>
<li>从浏览器创建 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequests</a></li>
<li>从 node.js 创建 <a target="_blank" rel="noopener" href="http://nodejs.org/api/http.html">http</a> 请求</li>
<li>支持 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> API</li>
<li>拦截请求和响应</li>
<li>转换请求和响应数据</li>
<li>取消请求</li>
<li>自动转换JSON数据</li>
<li>客户端支持防御<a target="_blank" rel="noopener" href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">XSRF</a></li>
</ul>
</blockquote>
</li>
<li><p>常用语法：</p>
<blockquote>
<p>（1）axios(config): 通用/最本质的发任意类型请求的方式</p>
<p>（2）axios(url[, config]): 可以只指定 url 发 get 请求</p>
<p>（3）axios.request(config): 等同于 axios(config)</p>
<p>（4）axios.get(url[, config]): 发 get 请求</p>
<p>（5）axios.delete(url[, config]): 发 delete 请求</p>
<p>（6）axios.post(url[, data, config]): 发 post 请求</p>
<p>（7）axios.put(url[, data, config]): 发 put 请求</p>
<p>（8）axios.defaults.xxx: 请求的默认全局配置</p>
<p>（9）axios.interceptors.request.use(): 添加请求拦截器</p>
<p>（10）axios.interceptors.response.use(): 添加响应拦截器</p>
<p>（11）axios.create([config]): 创建一个新的 axios(它没有下面的功能)</p>
<p>（12）axios.Cancel(): 用于创建取消请求的错误对象</p>
<p>（13）axios.CancelToken(): 用于创建取消请求的 token 对象</p>
<p>（14）axios.isCancel(): 是否是一个取消请求的错误</p>
<p>（15）axios.all(promises): 用于批量执行多个异步请求</p>
<p>（16）axios.spread(): 用来指定接收所有成功数据的回调函数的方法</p>
<p><img src= "" data-lazy-src="img/Axios.jpg" alt=""></p>
</blockquote>
</li>
</ol>
<h2 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h2><ol>
<li><p>配合 json-server 和 axios 基本使用</p>
</li>
<li><p>axios 是基于 promise 对 ajax 的封装</p>
</li>
<li><blockquote>
<ol>
<li><p>默认为 get，默认时 method 指定请求类型可不写</p>
</li>
<li><p>参数直接写 地址后追加 /id=2  /id=2等等</p>
</li>
<li><p>可使用链式编程的方式，在后面加 then（）加 catch</p>
</li>
<li><p>catch:检测错误</p>
</li>
<li><p>```js<br>   btn[0].addEventListener(‘click’, function () {</p>
<pre><code> // 发送 ajax 请求
 axios(&#123;
   // URL
   url: &#39;http://localhost:3000/posts/2&#39;,
 &#125;).then((value) =&gt; &#123;
   console.log(value)
 &#125;).catch((err)=&gt;&#123;
       console.log(err) // 检测错误
 &#125;)
</code></pre><p>   })</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">6. 使用 POST 传参</span><br><span class="line"></span><br><span class="line">7. ```js</span><br><span class="line">   axios.post(&#x27;http://localhost:3000/posts&#x27;,&#x27;name=张三&amp;age=10&#x27;).then(res=&gt;&#123;</span><br><span class="line">       console.log(res)</span><br><span class="line">   &#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p>并发请求</p>
</li>
<li><p>```js<br>// 方式一：<br>axios.all([</p>
<pre><code>axios.get(&#39;http://localhost:3000/posts&#39;),
axios.get(&#39;http://localhost:3000/posts/id&#39;,&#123;params:&#123;id:1&#125;&#125;),
</code></pre><p>]).then((res)=&gt;{</p>
<pre><code>console.log(res)
</code></pre><p>}).catch((err)=&gt;{</p>
<pre><code>console.log(err)
</code></pre><p>})</p>
<p>// 方式二 spread分割<br>axios.all([</p>
<pre><code>axios.get(&#39;http://localhost:3000/posts&#39;),
axios.get(&#39;http://localhost:3000/posts/id&#39;,&#123;params:&#123;id:1&#125;&#125;),
</code></pre><p>]).then(<br>axios.spread((res1,res2)=&gt;{</p>
<pre><code>console.log(res1)
console.log(res2)
</code></pre><p>})<br>).catch((err)=&gt;{</p>
<pre><code>console.log(err)
</code></pre><p>})</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">10.</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">```js</span><br><span class="line">   // 获取元素</span><br><span class="line">      const btn = document.querySelectorAll(&#x27;button&#x27;)</span><br><span class="line"></span><br><span class="line">      // 第一个</span><br><span class="line">      btn[0].addEventListener(&#x27;click&#x27;, function () &#123;</span><br><span class="line">        // 发送 ajax 请求</span><br><span class="line">        axios(&#123;</span><br><span class="line">          // 请求类型</span><br><span class="line">          method: &#x27;GET&#x27;,</span><br><span class="line">          // URL</span><br><span class="line">          url: &#x27; http://localhost:3000/posts/2&#x27;,</span><br><span class="line">        &#125;).then((value) =&gt; &#123;</span><br><span class="line">          console.log(value)</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;)</span><br><span class="line"></span><br><span class="line">      // 第二个，添加一篇新的文章</span><br><span class="line">      btn[1].addEventListener(&#x27;click&#x27;, function () &#123;</span><br><span class="line">        // 发送 ajax 请求</span><br><span class="line">        axios(&#123;</span><br><span class="line">          // 请求类型</span><br><span class="line">          method: &#x27;POST&#x27;,</span><br><span class="line">          // URL</span><br><span class="line">          url: &#x27; http://localhost:3000/posts&#x27;,</span><br><span class="line">          // 设置请求体</span><br><span class="line">          data: &#123;</span><br><span class="line">            title: &#x27;今天天气不错&#x27;,</span><br><span class="line">            author: &#x27;浩果锅&#x27;,</span><br><span class="line">          &#125;,</span><br><span class="line">        &#125;).then((value) =&gt; &#123;</span><br><span class="line">          console.log(value)</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;)</span><br><span class="line"></span><br><span class="line">      // 第三个,更新数据</span><br><span class="line">      btn[2].addEventListener(&#x27;click&#x27;, function () &#123;</span><br><span class="line">        // 发送 ajax 请求</span><br><span class="line">        axios(&#123;</span><br><span class="line">          // 请求类型</span><br><span class="line">          method: &#x27;PUT&#x27;,</span><br><span class="line">          // URL</span><br><span class="line">          url: &#x27; http://localhost:3000/posts/3&#x27;,</span><br><span class="line">          // 设置请求体</span><br><span class="line">          data: &#123;</span><br><span class="line">            title: &#x27;今天天气不错&#x27;,</span><br><span class="line">            author: &#x27;小鱼儿&#x27;,</span><br><span class="line">          &#125;,</span><br><span class="line">        &#125;).then((value) =&gt; &#123;</span><br><span class="line">          console.log(value)</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;)</span><br><span class="line"></span><br><span class="line">      // 第四个,删除数据</span><br><span class="line">      btn[3].addEventListener(&#x27;click&#x27;, function () &#123;</span><br><span class="line">        // 发送 ajax 请求</span><br><span class="line">        axios(&#123;</span><br><span class="line">          // 请求类型</span><br><span class="line">          method: &#x27;delete&#x27;,</span><br><span class="line">          // URL</span><br><span class="line">          url: &#x27; http://localhost:3000/posts/3&#x27;,</span><br><span class="line">          // 设置请求体</span><br><span class="line">        &#125;).then((value) =&gt; &#123;</span><br><span class="line">          console.log(value)</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;)</span><br></pre></td></tr></table></figure>
</li>
</ol>
</blockquote>
</li>
</ol>
<h1 id="axios-create-config"><a href="#axios-create-config" class="headerlink" title="axios.create(config)"></a>axios.create(config)</h1><blockquote>
<p>1、根据指定配置创建一个新的 axios, 也就就每个新 axios 都有自己的配置、</p>
<p>2、新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的</p>
<p>3、为什么要设计这个语法?</p>
<p>(1) 需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一</p>
<p>样, 如何处理</p>
<p>(2) 解决: 创建 2 个新 axios, 每个都有自己特有的配置, 分别应用到不同要</p>
<p>求的接口请求中</p>
</blockquote>
<h1 id="默认配置"><a href="#默认配置" class="headerlink" title="默认配置"></a>默认配置</h1><ol>
<li><p>```js<br>axios.defaults xxx</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">2. 例子：</span><br><span class="line"></span><br><span class="line">   &gt; ```js</span><br><span class="line">   &gt; axios.defaults.method = &#x27;get&#x27; // 设置默认的请求类型为 get</span><br><span class="line">   &gt; axios.defaults.methodURL = &#x27;http://localhost:3000&#x27; // 设置基础的 url</span><br><span class="line">   &gt; axios.defaults.params = &#123;id：100&#125; // 给地址追加 id 参数，值为100</span><br></pre></td></tr></table></figure>
</li>
<li><p>具体查文档</p>
</li>
</ol>
<h1 id="创建实例"><a href="#创建实例" class="headerlink" title="创建实例"></a>创建实例</h1><ol>
<li>```js<br>  // 获取元素<pre><code>  const btn = document.querySelectorAll(button)
  // 创建实例对象
  const dz = axios.create(&#123;
    daseURL: &#39;https://api.apiopen.top&#39;,
    timeout: 2000,
  &#125;)
  // 这里 dz 与 axios 对象的功能几近是一样的
  dz(&#123;
    url: &#39;/getJoke&#39;,
  &#125;).then((response) =&gt; &#123;
    console.log(response)
  &#125;)
</code></pre>  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">```js</span><br><span class="line">     // 和上面的效果一样</span><br><span class="line">     dz.get(&#x27;/getJoke&#x27;).then((response) =&gt; &#123;</span><br><span class="line">       console.log(response.data)</span><br><span class="line">     &#125;)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h1 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h1><blockquote>
<p>1、说明: 调用 axios()并不是立即发送 ajax 请求, 而是需要经历一个较长的流程</p>
<p>2、流程: 请求拦截器2 =&gt; 请求拦截器1 =&gt; 发ajax请求 =&gt; 响应拦截器1 =&gt; 响</p>
<p>应拦截器 2 =&gt; 请求的回调</p>
<p>3、注意: 此流程是通过 promise 串连起来的, 请求拦截器传递的是 config, 响应</p>
<p>拦截器传递的是 response</p>
<p>4、axios 给我们提供了两大类拦截器，</p>
<p>（1）一种是请求方向的拦截（成功请求，失败请求）</p>
<p>（2）另一种是响应方向的拦截（成功请求，失败请求）</p>
<p>5、拦截器的作用：</p>
<p>（1）用于我们在网络请求的时候在发起请求或者响应时对操作进行响应的处理</p>
<p>（2）例如：</p>
<p>​    a、发起请求时，可以添加网页的加载动画，</p>
<p>​    b、使用 token 认证时的强制登录，可以进行响应的数据处理等</p>
</blockquote>
<ol>
<li><p>```js</p>
<pre><code>// 添加请求拦截器
  axios.interceptors.request.use(
    function (config) &#123;
      console.log(&#39;请求拦截器,成功&#39;)
      // 在发送请求之前做些什么
      // return config 请求后一定要 放行，不然接收不到
      throw &#39;参数出了问题&#39;
    &#125;,

    function (error) &#123;
      console.log(&#39;请求拦截器,失败&#39;)
      // 对请求错误做些什么
      return Promise.reject(error)
    &#125;
  )

  // 添加响应拦截器
  axios.interceptors.response.use(
    function (response) &#123;
      console.log(&#39;响应拦截器 成功&#39;)
      // 2xx 范围内的状态码都会触发该函数。
      // 对响应数据做点什么
      return response
    &#125;,
    function (error) &#123;
      console.log(&#39;响应拦截器 失败&#39;)
      // 超出 2xx 范围的状态码都会触发该函数。
      // 对响应错误做点什么
      return Promise.reject(error)
    &#125;
  )

  // 发送请求
  axios(&#123;
    method: &#39;get&#39;,
    url: &#39;http://localhost:3000/posts&#39;,
  &#125;)
    .then((response) =&gt; &#123;
      //
      console.log(&#39;自定义回调处理成功的结果&#39;)
      console.log(response)
    &#125;)
    .catch((error) =&gt; &#123;
      console.log(&#39;自定义失败的回调&#39;)
    &#125;)
</code></pre><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># 请求取消</span><br><span class="line"></span><br><span class="line">&gt; 1、基本流程</span><br><span class="line">&gt;</span><br><span class="line">&gt; （1）配置 cancelToken 对象</span><br><span class="line">&gt;</span><br><span class="line">&gt; （2）缓存用于取消请求的 cancel 函数</span><br><span class="line">&gt;</span><br><span class="line">&gt; （3）在后面特定时机调用 cancel 函数取消请求</span><br><span class="line">&gt;</span><br><span class="line">&gt; （4）在错误回调中判断如果 error 是 cancel, 做相应处理</span><br><span class="line">&gt;</span><br><span class="line">&gt; 2、实现功能</span><br><span class="line">&gt;</span><br><span class="line">&gt; （1）点击按钮, 取消某个正在请求中的请求</span><br><span class="line">&gt;</span><br><span class="line">&gt; （2）在请求一个接口前, 取消前面一个未完成的请求</span><br><span class="line"></span><br><span class="line">1. 先 添加相关配置项</span><br><span class="line"></span><br><span class="line">   &gt; ```js</span><br><span class="line">   &gt;     // 声明全局变量</span><br><span class="line">   &gt;       let cance = null</span><br><span class="line">   &gt;</span><br><span class="line">   &gt; cancelToken: new axios.CancelToken(function (c) &#123;</span><br><span class="line">   &gt;             // 3.将 c 的值赋值给 cance</span><br><span class="line">   &gt;             cance = c</span><br><span class="line">   &gt;           &#125;),</span><br></pre></td></tr></table></figure>
</li>
<li><p>再检测上一次请求是否成功</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">     <span class="comment">// 检测上一次请求是否完成,就是判断 cance 的值是不是 null</span></span><br><span class="line"><span class="keyword">if</span> (cance !== <span class="literal">null</span>) &#123;</span><br><span class="line">       <span class="comment">// 取消上一次请求</span></span><br><span class="line">       <span class="title function_">cance</span>()</span><br><span class="line">     &#125;</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>如果上一次请求成功，就将 cance 的值 变为 null</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">.<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(response)</span><br><span class="line">     <span class="comment">// 将 请求变为空</span></span><br><span class="line">     cance = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>完整代码</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取元素</span></span><br><span class="line">   <span class="keyword">const</span> btn = <span class="variable language_">document</span>.<span class="title function_">querySelectorAll</span>(<span class="string">&#x27;button&#x27;</span>)</span><br><span class="line">   <span class="comment">// 声明全局变量</span></span><br><span class="line">   <span class="keyword">let</span> cance = <span class="literal">null</span></span><br><span class="line">   <span class="comment">// 发送请求</span></span><br><span class="line">   btn[<span class="number">0</span>].<span class="title function_">addEventListener</span>(<span class="string">&#x27;click&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">     <span class="comment">// 检测上一次请求是否完成,就是判断 cance 的值是不是 null</span></span><br><span class="line">     <span class="keyword">if</span> (cance !== <span class="literal">null</span>) &#123;</span><br><span class="line">       <span class="comment">// 取消上一次请求</span></span><br><span class="line">       <span class="title function_">cance</span>()</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="title function_">axios</span>(&#123;</span><br><span class="line">       <span class="attr">method</span>: <span class="string">&#x27;get&#x27;</span>,</span><br><span class="line">       <span class="attr">url</span>: <span class="string">&#x27;http://localhost:3000/posts&#x27;</span>,</span><br><span class="line">       <span class="comment">// 添加配置对象的属性</span></span><br><span class="line">       <span class="attr">cancelToken</span>: <span class="keyword">new</span> axios.<span class="title class_">CancelToken</span>(<span class="keyword">function</span> (<span class="params">c</span>) &#123;</span><br><span class="line">         <span class="comment">// 3.将 c 的值赋值给 cance</span></span><br><span class="line">         cance = c</span><br><span class="line">       &#125;),</span><br><span class="line">     &#125;).<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> &#123;</span><br><span class="line">       <span class="variable language_">console</span>.<span class="title function_">log</span>(response)</span><br><span class="line">       <span class="comment">// 将 请求变为空</span></span><br><span class="line">       cance = <span class="literal">null</span></span><br><span class="line">     &#125;)</span><br><span class="line">   &#125;)</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 取消请求</span></span><br><span class="line">   btn[<span class="number">1</span>].<span class="title function_">addEventListener</span>(<span class="string">&#x27;click&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">     <span class="title function_">cance</span>()</span><br><span class="line">   &#125;)</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>
<h1 id="源码：分析"><a href="#源码：分析" class="headerlink" title="源码：分析"></a>源码：分析</h1><ol>
<li>源码目录结构图</li>
<li><img src= "" data-lazy-src="img/%E6%BA%90%E7%A0%81%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84.jpg" alt=""></li>
</ol>
<h2 id="axios-与-Axios-的关系"><a href="#axios-与-Axios-的关系" class="headerlink" title="axios 与 Axios 的关系"></a>axios 与 Axios 的关系</h2><blockquote>
<p>1、从语法上来说: axios 不是 Axios 的实例</p>
<p>2、从功能上来说: axios 是 Axios 的实例</p>
<p>3、axios 是 Axios.prototype.request 函数 bind()返回的函数</p>
<p>4、axios 作为对象有 Axios 原型对象上的所有方法, 有 Axios 对象上所有属性</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 构造函数</span></span><br><span class="line">   <span class="keyword">function</span> <span class="title function_">Axios</span>(<span class="params">config</span>) &#123;</span><br><span class="line">     <span class="comment">// 初始化</span></span><br><span class="line">     <span class="variable language_">this</span>.<span class="property">defaults</span> = config <span class="comment">// 为了创建 default 默认属性</span></span><br><span class="line">     <span class="variable language_">this</span>.<span class="property">interceptors</span> = &#123;</span><br><span class="line">       <span class="attr">request</span>: &#123;&#125;,</span><br><span class="line">       <span class="attr">response</span>: &#123;&#125;,</span><br><span class="line">     &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">// 原型添加相关的方法，能发送 ajax 请求的原因，是因为内部调用了 ajax 的方法</span></span><br><span class="line">   <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">request</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;发送 Ajax 请求,请求的类型为&#x27;</span> + config.<span class="property">method</span>)</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">get</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">     <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">request</span>(&#123; <span class="attr">method</span>: <span class="string">&#x27;GET&#x27;</span> &#125;)</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">post</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">     <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">request</span>(&#123; <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span> &#125;)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 声明函数</span></span><br><span class="line">   <span class="keyword">function</span> <span class="title function_">createInstance</span>(<span class="params">config</span>) &#123;</span><br><span class="line">     <span class="comment">// 实例化一个对象</span></span><br><span class="line">     <span class="keyword">let</span> context = <span class="keyword">new</span> <span class="title class_">Axios</span>(config) <span class="comment">// context.get() context.post()    但是不能当做函数使用 context()</span></span><br><span class="line">     <span class="comment">// 创建请求函数</span></span><br><span class="line">     <span class="keyword">let</span> instance = <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">request</span>.<span class="title function_">bind</span>(context) <span class="comment">// instance 是一个函数 并且可以 instance(&#123;&#125;) ,此时 instance 不能当做对象使用</span></span><br><span class="line">     <span class="comment">// 将 Axios.prototype 对象中的方法添加到 instance 函数对象中</span></span><br><span class="line">     <span class="title class_">Object</span>.<span class="title function_">keys</span>(<span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>).<span class="title function_">forEach</span>(<span class="function">(<span class="params">key</span>) =&gt;</span> &#123;</span><br><span class="line">       instance[key] = <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>[key].<span class="title function_">bind</span>(context) <span class="comment">// this.default   this.interceptors</span></span><br><span class="line">     &#125;)</span><br><span class="line">     <span class="comment">// 为 instance 函数对象添加属性 default 与 interceptors</span></span><br><span class="line">     <span class="title class_">Object</span>.<span class="title function_">keys</span>(context).<span class="title function_">forEach</span>(<span class="function">(<span class="params">key</span>) =&gt;</span> &#123;</span><br><span class="line">       instance[key] = context[key]</span><br><span class="line">     &#125;)</span><br><span class="line">     <span class="keyword">return</span> instance</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 测试</span></span><br><span class="line">   <span class="keyword">let</span> axios = <span class="title function_">createInstance</span>()</span><br><span class="line">   <span class="comment">// 发送请求</span></span><br><span class="line">   <span class="title function_">axios</span>(&#123; <span class="attr">method</span>: <span class="string">&#x27;GET&#x27;</span> &#125;)</span><br></pre></td></tr></table></figure>
</blockquote>
<h2 id="instance-与-axios-的区别"><a href="#instance-与-axios-的区别" class="headerlink" title="instance 与 axios 的区别 ?"></a>instance 与 axios 的区别 ?</h2><blockquote>
<p>1、相同：</p>
<p>（1）都是一个能发任意请求的函数: request(config)</p>
<p>（2）都有发特定请求的各种方法: get()/post()/put()/delete()</p>
<p>（3）都有默认配置和拦截器的属性: defaults/interceptors</p>
<p>2、不同:</p>
<p>（1）默认配置很可能不一样</p>
<p>（2）instance 没有 axios 后面添加的一些方法: create()/CancelToken()/all()</p>
</blockquote>
<h2 id="axios-运行流程图"><a href="#axios-运行流程图" class="headerlink" title="axios 运行流程图"></a>axios 运行流程图</h2><ol>
<li><p><img src= "" data-lazy-src="img/axios%20%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%9B%BE.png" alt=""></p>
</li>
<li><p>整体流程:</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">request</span>(config) ==&gt; <span class="title function_">dispatchRequest</span>(config) ==&gt; <span class="title function_">xhrAdapter</span>(config)</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>request(config):</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">将请求拦截器 / <span class="title function_">dispatchRequest</span>() / 响应拦截器 通过 promise 链串连起来,</span><br><span class="line"></span><br><span class="line">返回 promise</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>dispatchRequest(config):</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">转换请求数据 ===&gt; 调用 <span class="title function_">xhrAdapter</span>()发请求 ===&gt; 请求返回后转换响应数</span><br><span class="line"></span><br><span class="line">据. 返回 promise</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>xhrAdapter(config):</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">创建 <span class="variable constant_">XHR</span> 对象, 根据 config 进行相应设置, 发送特定请求, 并接收响应数据,</span><br><span class="line"></span><br><span class="line">返回 promise</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// axios 发送请求的过程 axios Axios.prototype.requset bind axios 的创建过程</span></span><br><span class="line">   <span class="comment">// 1.声明构造函数</span></span><br><span class="line">   <span class="keyword">function</span> <span class="title function_">Axios</span>(<span class="params">config</span>) &#123;</span><br><span class="line">     <span class="variable language_">this</span>.<span class="property">config</span> = config</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">requset</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">     <span class="comment">// 发送请求</span></span><br><span class="line">     <span class="comment">// 创建了一个 Promise 对象</span></span><br><span class="line">     <span class="keyword">let</span> promise = <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(config)</span><br><span class="line">     <span class="comment">// 声明一个数组</span></span><br><span class="line">     <span class="keyword">let</span> chains = [dispatchRequest, <span class="literal">undefined</span>] <span class="comment">// undefined 占位</span></span><br><span class="line">     <span class="comment">// 调用 then 方法指定回调</span></span><br><span class="line">     <span class="keyword">let</span> result = promise.<span class="title function_">then</span>(chains[<span class="number">0</span>], chains[<span class="number">1</span>])</span><br><span class="line">     <span class="comment">// 返回 promise 的结果</span></span><br><span class="line">     <span class="keyword">return</span> result</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">// 2.dispatchRequest 函数</span></span><br><span class="line">   <span class="keyword">function</span> <span class="title function_">dispatchRequest</span>(<span class="params">config</span>) &#123;</span><br><span class="line">     <span class="keyword">return</span> <span class="title function_">xhrAdapter</span>(config).<span class="title function_">then</span>(</span><br><span class="line">       <span class="function">(<span class="params">response</span>) =&gt;</span> &#123;</span><br><span class="line">         <span class="comment">// 响应结果进行转换处理</span></span><br><span class="line">         <span class="keyword">return</span> response</span><br><span class="line">       &#125;,</span><br><span class="line">       <span class="function">(<span class="params">error</span>) =&gt;</span> &#123;</span><br><span class="line">         <span class="keyword">throw</span> error</span><br><span class="line">       &#125;</span><br><span class="line">     )</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 3.adapter 适配器</span></span><br><span class="line">   <span class="keyword">function</span> <span class="title function_">xhrAdapter</span>(<span class="params">config</span>) &#123;</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;xhrAdapter 函数执行&#x27;</span>)</span><br><span class="line">     <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">       <span class="comment">// 发送 Ajax 请求</span></span><br><span class="line">       <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>()</span><br><span class="line">       <span class="comment">// 初始化</span></span><br><span class="line">       xhr.<span class="title function_">open</span>(config.<span class="property">method</span>, config.<span class="property">url</span>)</span><br><span class="line">       <span class="comment">// 发送</span></span><br><span class="line">       xhr.<span class="title function_">send</span>()</span><br><span class="line">       <span class="comment">// 绑定</span></span><br><span class="line">       xhr.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">         <span class="keyword">if</span> (xhr.<span class="property">readyState</span> == <span class="number">4</span>) &#123;</span><br><span class="line">           <span class="keyword">if</span> (xhr.<span class="property">status</span> &gt;= <span class="number">200</span> &amp;&amp; xhr.<span class="property">status</span> &lt; <span class="number">300</span>) &#123;</span><br><span class="line">             <span class="comment">// 成功的状态</span></span><br><span class="line">             <span class="title function_">resolve</span>(&#123;</span><br><span class="line">               <span class="comment">// 配置对象</span></span><br><span class="line">               <span class="attr">config</span>: config,</span><br><span class="line">               <span class="comment">// 响应体</span></span><br><span class="line">               <span class="attr">data</span>: xhr.<span class="property">response</span>,</span><br><span class="line">               <span class="comment">// 响应头</span></span><br><span class="line">               <span class="attr">headers</span>: xhr.<span class="title function_">getAllResponseHeaders</span>(), <span class="comment">//字符串</span></span><br><span class="line">               <span class="comment">// xhr的请求对象</span></span><br><span class="line">               <span class="attr">request</span>: xhr,</span><br><span class="line">               <span class="comment">// 响应状态码</span></span><br><span class="line">               <span class="attr">status</span>: xhr.<span class="property">status</span>,</span><br><span class="line">               <span class="comment">// 响应状态字符串</span></span><br><span class="line">               <span class="attr">statusText</span>: xhr.<span class="property">statusText</span>,</span><br><span class="line">             &#125;)</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">             <span class="comment">// 失败的状态</span></span><br><span class="line">             <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;请求失败,失败的状态码为&#x27;</span> + xhr.<span class="property">status</span>))</span><br><span class="line">           &#125;</span><br><span class="line">         &#125;</span><br><span class="line">       &#125;</span><br><span class="line">     &#125;)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 4.创建 axios 函数</span></span><br><span class="line">   <span class="keyword">let</span> axios = <span class="title class_">Axios</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">requset</span>.<span class="title function_">bind</span>(<span class="literal">null</span>)</span><br><span class="line"></span><br><span class="line">   <span class="title function_">axios</span>(&#123;</span><br><span class="line">     <span class="attr">method</span>: <span class="string">&#x27;GET&#x27;</span>,</span><br><span class="line">     <span class="attr">url</span>: <span class="string">&#x27;http://localhost:3000/posts&#x27;</span>,</span><br><span class="line">   &#125;).<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> &#123;</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(response)</span><br><span class="line">   &#125;)</span><br></pre></td></tr></table></figure>
<h2 id="拦截器是什么"><a href="#拦截器是什么" class="headerlink" title="拦截器是什么"></a>拦截器是什么</h2><ol>
<li><p><img src= "" data-lazy-src="img/%E6%8B%A6%E6%88%AA%E5%99%A8%E6%98%AF%E4%BB%80%E4%B9%88.png" alt=""></p>
</li>
<li><p>请求拦截器:</p>
<blockquote>
<p>（1）在真正发送请求前执行的回调函数</p>
<p>（2）可以对请求进行检查或配置进行特定处理</p>
<p>（3）成功的回调函数, 传递的默认是 config(也必须是)</p>
<p>（4）失败的回调函数, 传递的默认是 error</p>
</blockquote>
</li>
<li><p>响应拦截器：</p>
<blockquote>
<p>（1）在请求得到响应后执行的回调函数</p>
<p>（2）可以对响应数据进行特定处理</p>
<p>（3）成功的回调函数, 传递的默认是 response</p>
<p>（4）失败的回调函数, 传递的默认是 error</p>
</blockquote>
</li>
</ol>
<h2 id="axios-的请求-响应数据转换器是什么"><a href="#axios-的请求-响应数据转换器是什么" class="headerlink" title="axios 的请求 / 响应数据转换器是什么 ?"></a>axios 的请求 / 响应数据转换器是什么 ?</h2><ol>
<li><p>请求转换器: 对请求头和请求体数据进行特定处理的函数</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (utils.<span class="title function_">isObject</span>(data)) &#123;</span><br><span class="line"> <span class="title function_">setContentTypeIfUnset</span>(headers, <span class="string">&#x27;application/json;charset=utf-8&#x27;</span>);</span><br><span class="line"> <span class="keyword">return</span> <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>响应转换器: 将响应体 json 字符串解析为 js 对象或数组的函数</p>
<blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">response.<span class="property">data</span> = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(response.<span class="property">data</span>)</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>
<h2 id="response-的整体结构"><a href="#response-的整体结构" class="headerlink" title="response 的整体结构"></a>response 的整体结构</h2><ol>
<li>```js<br>{<br> data,<br> status,<br> statusText,<br> headers,<br> config,<br> request<br> }<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">## error 的整体结构</span><br><span class="line"></span><br><span class="line">1. ```js</span><br><span class="line">   &#123;</span><br><span class="line">    message,</span><br><span class="line">    response,</span><br><span class="line">    request,</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="如何取消未完成的请求"><a href="#如何取消未完成的请求" class="headerlink" title="如何取消未完成的请求?"></a>如何取消未完成的请求?</h2><blockquote>
<p>1、当配置了 cancelToken 对象时, 保存 cancel 函数</p>
<p>（1）创建一个用于将来中断请求的 cancelPromise</p>
<p>（2）并定义了一个用于取消请求的 cancel 函数</p>
<p>（3）将 cancel 函数传递出来</p>
<p>2、调用 cancel()取消请求</p>
<p>（1）执行 cacel 函数, 传入错误信息 message</p>
<p>（2） 内部会让 cancelPromise 变为成功, 且成功的值为一个 Cancel 对象</p>
<p>（3）在 cancelPromise 的成功回调中中断请求, 并让发请求的 proimse 失败, 失败的 reason 为 Cancel 对象</p>
</blockquote>
<h1 id="在-Vue-中封装使用-axios"><a href="#在-Vue-中封装使用-axios" class="headerlink" title="在 Vue 中封装使用 axios"></a>在 Vue 中封装使用 axios</h1><ol>
<li><p>```js<br>// 方法一：<br>// 封住位置，封装在一个文件夹下的.脚本文件中<br>import axios from ‘axios’<br>export function(config,success,fail){</p>
<pre><code>axios(&#123;
    url:config
&#125;).then(err=&gt;&#123;
    success(res)
&#125;).catch(err=&gt;&#123;
    fail(err)
&#125;)
</code></pre><p>}</p>
<p>// 调用者位置<br>// 在 main.js 中导入使用<br>import {request} from ‘./request/request.js’<br>request(config:’<a target="_blank" rel="noopener" href="http://localhost/request&#39;,success:res=&gt;{">http://localhost/request&#39;,success:res=&gt;{</a></p>
<pre><code> console.log(res)
</code></pre><p>},fail.err=&gt;{</p>
<pre><code>console,log(err)
</code></pre><p>})</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">2. ```js</span><br><span class="line">   // 方式二：</span><br><span class="line">   // 封住位置，封装在一个文件夹下的.脚本文件中</span><br><span class="line">   import axios from &#x27;axios&#x27;</span><br><span class="line">   export function(config,success,fail)&#123;</span><br><span class="line">       axios(config.url).then(</span><br><span class="line">       res=&gt;&#123;</span><br><span class="line">           config.success(res)</span><br><span class="line">       	&#125;</span><br><span class="line">       ).catch(err=&gt;&#123;</span><br><span class="line">           config.fail(err)</span><br><span class="line">       &#125;)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   // 调用者位置</span><br><span class="line">   // 在 main.js 中导入使用</span><br><span class="line">   import &#123;request&#125; from &#x27;./request/request.js&#x27;</span><br><span class="line">   request(config:&#123;</span><br><span class="line">           url:&#x27;getAll&#x27;,</span><br><span class="line">           success:res=&gt;&#123;</span><br><span class="line">           console.log(res)</span><br><span class="line">           &#125;,</span><br><span class="line">               fail:err=&gt;&#123;</span><br><span class="line">                   console.log(err)</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>3.</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">晚夜微雨问海棠</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/posts/6155a9d6.html">http://example.com/posts/6155a9d6.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">晚夜微雨问海棠のBlog</a>！</span></div></div><div class="tag_share"><div class="post_share"><div class="social-share" data-image="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pianshen.com%2Fimages%2F392%2Fc8f82846ea9401c8fbcb4428a7269870.png&amp;refer=http%3A%2F%2Fwww.pianshen.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1664443051&amp;t=4db5e4c8373f1a1e24d8a9a048367a1b" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://s1.ax1x.com/2022/11/15/zE9P7d.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://s1.ax1x.com/2022/11/15/zE9P7d.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://s1.ax1x.com/2022/11/15/zE9ung.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://s1.ax1x.com/2022/11/15/zE9ung.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Json-server-%E5%8C%85-%E6%90%AD%E5%BB%BAREST-API"><span class="toc-number">1.</span> <span class="toc-text">Json-server 包 搭建REST API</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#json-server-%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">1.1.</span> <span class="toc-text">json-server 是什么？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-json-server"><span class="toc-number">1.2.</span> <span class="toc-text">使用 json-server</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#axios"><span class="toc-number">2.</span> <span class="toc-text">axios</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">2.1.</span> <span class="toc-text">安装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-number">2.2.</span> <span class="toc-text">基本使用</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#axios-create-config"><span class="toc-number">3.</span> <span class="toc-text">axios.create(config)</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%BB%98%E8%AE%A4%E9%85%8D%E7%BD%AE"><span class="toc-number">4.</span> <span class="toc-text">默认配置</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BE%8B"><span class="toc-number">5.</span> <span class="toc-text">创建实例</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-number">6.</span> <span class="toc-text">拦截器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%EF%BC%9A%E5%88%86%E6%9E%90"><span class="toc-number">7.</span> <span class="toc-text">源码：分析</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#axios-%E4%B8%8E-Axios-%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="toc-number">7.1.</span> <span class="toc-text">axios 与 Axios 的关系</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#instance-%E4%B8%8E-axios-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">7.2.</span> <span class="toc-text">instance 与 axios 的区别 ?</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#axios-%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="toc-number">7.3.</span> <span class="toc-text">axios 运行流程图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8B%A6%E6%88%AA%E5%99%A8%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">7.4.</span> <span class="toc-text">拦截器是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#axios-%E7%9A%84%E8%AF%B7%E6%B1%82-%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE%E8%BD%AC%E6%8D%A2%E5%99%A8%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">7.5.</span> <span class="toc-text">axios 的请求 &#x2F; 响应数据转换器是什么 ?</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#response-%E7%9A%84%E6%95%B4%E4%BD%93%E7%BB%93%E6%9E%84"><span class="toc-number">7.6.</span> <span class="toc-text">response 的整体结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E5%8F%96%E6%B6%88%E6%9C%AA%E5%AE%8C%E6%88%90%E7%9A%84%E8%AF%B7%E6%B1%82"><span class="toc-number">7.7.</span> <span class="toc-text">如何取消未完成的请求?</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9C%A8-Vue-%E4%B8%AD%E5%B0%81%E8%A3%85%E4%BD%BF%E7%94%A8-axios"><span class="toc-number">8.</span> <span class="toc-text">在 Vue 中封装使用 axios</span></a></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pianshen.com%2Fimages%2F392%2Fc8f82846ea9401c8fbcb4428a7269870.png&amp;refer=http%3A%2F%2Fwww.pianshen.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1664443051&amp;t=4db5e4c8373f1a1e24d8a9a048367a1b')"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By 晚夜微雨问海棠</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>(() => {
  const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaidWrap.length) {
    window.runMermaid = () => {
      window.loadMermaid = true
      const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

      Array.from($mermaidWrap).forEach((item, index) => {
        const mermaidSrc = item.firstElementChild
        const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
        const mermaidID = 'mermaid-' + index
        const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
        mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
          mermaidSrc.insertAdjacentHTML('afterend', svgCode)
        })
      })
    }

    const loadMermaid = () => {
      window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
    }

    window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
  }
})()</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="7625372994" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true"> </div> <script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script> <script src="/swiper/swiper.min.js"></script> <script src="/swiper/swiperindex.js"></script> <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script> <script src="/js/title.js"></script> <script defer data-pjax src="/js/cat.js"></script> <script defer data-pjax src="/js/rightMenu.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show","#web_bg",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>function history_calendar_injector_config(){
                var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
                var item_html = '<div class="card-widget card-history"><div class="card-content"><div class="item-headline"><i class="fas fa-clock fa-spin"></i><span>那年今日</span></div><div id="history-baidu" style="height: 100px;overflow: hidden"><div class="history_swiper-container" id="history-container" style="width: 100%;height: 100%"><div class="swiper-wrapper" id="history_container_wrapper" style="height:20px"></div></div></div></div>';
                console.log('已挂载history_calendar')
                // parent_div_git.innerHTML=item_html+parent_div_git.innerHTML // 无报错，但不影响使用(支持pjax跳转)
                parent_div_git.insertAdjacentHTML("afterbegin",item_html) // 有报错，但不影响使用(支持pjax跳转)
            }if( document.getElementsByClassName('sticky_layout')[0] && (location.pathname ==='/'|| '/' ==='all')){

            history_calendar_injector_config()
        } </script><script data-pjax  src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script><script data-pjax src="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-card-history/baiduhistory/js/main.js"></script><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:24%;}.categoryBar-list{max-height: 190px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 160px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpicnew6.photophoto.cn%2F20120106%2Fhaimianbaobaotupian-10036689_1.jpg&amp;refer=http%3A%2F%2Fpicnew6.photophoto.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1665648815&amp;t=a3deb15ddd7a38597964c3a05e519bd7);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Asp-Net/&quot;);" href="javascript:void(0);">Asp.Net</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://npm.elemecdn.com/anzhiyu-blog@1.1.6/img/post/common/site-backgound.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-系列/&quot;);" href="javascript:void(0);">C#系列</a><span class="categoryBar-list-count">8</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13012860773%2F1000.jpg&amp;refer=http%3A%2F%2Finews.gtimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1665648865&amp;t=1d2f13b52a7e279e8801545f59eda4e7);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Hexo重装记录/&quot;);" href="javascript:void(0);">Hexo重装记录</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202011%2F07%2F20201107183300_ac0c5.thumb.1000_0.jpeg&amp;refer=http%3A%2F%2Fc-ssl.duitang.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1665648887&amp;t=3d32c6b12a4cf12e5cec3585b79c1fc3);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/EF/&quot;);" href="javascript:void(0);">EF</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F25%2Feb%2F1f%2F25eb1fd40b5a740c2b79e33f700806e5.jpg&amp;refer=http%3A%2F%2Fup.enterdesk.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1665648908&amp;t=6425ee3bd166b0f5c5ffa6fb18b6937b);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/LOL/&quot;);" href="javascript:void(0);">LOL</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Flmg.jj20.com%2Fup%2Fallimg%2Ftx26%2F36080017392073.jpg&amp;refer=http%3A%2F%2Flmg.jj20.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1665650136&amp;t=5cc414d0ee58c9e285218d92f6a95513);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/idea/&quot;);" href="javascript:void(0);">idea</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn10%2F320%2Fw700h420%2F20180907%2F5116-hitesuz6599636.jpg&amp;refer=http%3A%2F%2Fn.sinaimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1665650004&amp;t=6a304aa9cc7435ec1d148b8f99092bc0);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/世界/&quot;);" href="javascript:void(0);">世界</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAxCi6.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/世界见闻录/&quot;);" href="javascript:void(0);">世界见闻录</a><span class="categoryBar-list-count">8</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAxFzD.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/前端体系/&quot;);" href="javascript:void(0);">前端体系</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAxnot.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/副业/&quot;);" href="javascript:void(0);">副业</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAxMJf.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/文案/&quot;);" href="javascript:void(0);">文案</a><span class="categoryBar-list-count">6</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAxQW8.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/办公日常/&quot;);" href="javascript:void(0);">办公日常</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAx3Qg.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/朝花夕拾/&quot;);" href="javascript:void(0);">朝花夕拾</a><span class="categoryBar-list-count">12</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(https://s1.ax1x.com/2022/11/15/zAxYes.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/前端/&quot;);" href="javascript:void(0);">前端</a><span class="categoryBar-list-count">20</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(undefined);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/杂七杂八/&quot;);" href="javascript:void(0);">杂七杂八</a><span class="categoryBar-list-count">7</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(undefined);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/简书/&quot;);" href="javascript:void(0);">简书</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(undefined);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/游戏/&quot;);" href="javascript:void(0);">游戏</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src= "" data-lazy-src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var qweather_key = '41ea442da35546559913a6a5d54163b2';
  var gaud_map_key = '6b62fbebf584b9a22a85bfccbf90335e';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '114.35,34.79';
  var clock_default_rectangle_enable = 'true';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo_v5.4.0" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" data-title="主题版本Butterfly_v4.2.2" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a><a class="github-badge" target="_blank" href="https://www.jsdelivr.com/" style="margin-inline:5px" data-title="本站使用JsDelivr为静态资源提供CDN加速" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&amp;logo=jsDelivr" alt=""/></a><a class="github-badge" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" style="margin-inline:5px" data-title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&amp;logo=Claris" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="/js/runtime/runtime.min.js"></script><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item swiper_container_card" style="height: auto;width: 100%"><div id="random"><div id="random-banner"><canvas id="peoplecanvas"></canvas></div><a id="random-hover" style="width:100%;height:auto;" href="javascript:toRandomPost()" rel="external nofollow noreferrer" one-link-mark="yes"><i class="fa fa-paper-plane" style="margin-left:10px"></i><div style="margin-left:10px">随便逛逛<i class="fa-solid fa-arrow-right" style="margin-left:10px"></i></div></a></div><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/67fcd28d.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://img2.baidu.com/it/u=4087346614,241521689&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=333" alt="" onerror="this.src=https://cdn.cbd.int/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2022-09-19</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/67fcd28d.html&quot;);" href="javascript:void(0);" alt="">学生人到职业人_心态篇</a><div class="blog-slider__text">再怎么看我也不知道怎么描述它的啦！</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/67fcd28d.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/8a73f76c.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://s1.ax1x.com/2022/11/04/xLiBTA.jpg" alt="" onerror="this.src=https://cdn.cbd.int/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2022-11-04</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/8a73f76c.html&quot;);" href="javascript:void(0);" alt="">生活の奇思妙想☞2022</a><div class="blog-slider__text">再怎么看我也不知道怎么描述它的啦！</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/8a73f76c.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/14e5dae6.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://s1.ax1x.com/2022/10/21/xcAQDH.jpg" alt="" onerror="this.src=https://cdn.cbd.int/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2022-11-12</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/14e5dae6.html&quot;);" href="javascript:void(0);" alt="">少年自负凌云笔</a><div class="blog-slider__text">再怎么看我也不知道怎么描述它的啦！</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/14e5dae6.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/9b7092b7.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://s1.ax1x.com/2022/10/11/xNJbF0.jpg" alt="" onerror="this.src=https://cdn.cbd.int/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2022-09-13</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/9b7092b7.html&quot;);" href="javascript:void(0);" alt="">租房有感</a><div class="blog-slider__text">再怎么看我也不知道怎么描述它的啦！</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/9b7092b7.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/94bbc7d.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://s1.ax1x.com/2022/10/11/xNJLWT.jpg" alt="" onerror="this.src=https://cdn.cbd.int/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2022-09-25</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/94bbc7d.html&quot;);" href="javascript:void(0);" alt="">谷歌收藏</a><div class="blog-slider__text">再怎么看我也不知道怎么描述它的啦！</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/94bbc7d.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/3b350f14.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://s1.ax1x.com/2022/10/11/xNJJd1.jpg" alt="" onerror="this.src=https://cdn.cbd.int/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2022-09-13</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/3b350f14.html&quot;);" href="javascript:void(0);" alt="">阳光不燥、微风正好</a><div class="blog-slider__text">再怎么看我也不知道怎么描述它的啦！</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/3b350f14.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/anzhiyu-blog@1.1.6/js/swiper.min.js"></script><script defer data-pjax src="https://cdn.cbd.int/hexo-butterfly-swiper-anzhiyu@1.0.4/lib/swiper_init.js"></script><script data-pjax src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/gsap/3.9.1/gsap.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper-anzhiyu@1.0.4/lib/people.min.js"></script><script async src="/anzhiyu/random.js"></script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '1.5s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('flink-list-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInY');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('flink-list-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__animated');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('article-sort-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__slideInRight');
    arr[i].setAttribute('data-wow-duration', '1.5s');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('site-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInY');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('site-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__animated');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://cdn.cbd.int/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://cdn.cbd.int/hexo-butterfly-wowjs/lib/wow_init.js"></script><script async src="/js/ali_font.js"></script><!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script></body></html>